import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/detail/lock_detail_notifier.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/show_datetime_picker.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:ttlock_flutter/ttlock.dart";

enum UsageTimeType {
  usage, // 限时
  single, // 单次
  forever, // 永久
  custom, // 自定义
  clear, // 清空
  cycle, // 循环
}

class TabPane extends StatefulWidget {
  final UsageTimeType usageTimeType;
  final Map lockInfo;
  const TabPane({super.key, required this.usageTimeType, required this.lockInfo});

  @override
  State<StatefulWidget> createState() => _TabPaneState();

}

class _TabPaneState extends State<TabPane> {

  bool forever = false;
  bool _getPwded = false;
  final DateTime currentDate = DateTime.now();
  String _returnedPwd = "";
  final Map _params = {
    "name": "",
    "startDate": DateTime.now(),
    "endDate": DateTime.now(),
    "keyboardPwd": "",
    "addType": 2, // 1：上传密码，2：网关添加，默认为2
    "keyboardPwdType": 3, // 默认期限密码
    "startTime": "00:00",
    "endTime": "23:59",
  };

  // 循环类型列表
  final List<Map<String, dynamic>> _cycleTypes = [
    {"name": "周末循环", "value": 5, "desc": "每周六周日在设定时间段内有效"},
    {"name": "每日循环", "value": 6, "desc": "每天在设定时间段内有效"},
    {"name": "工作日循环", "value": 7, "desc": "周一至周五在设定时间段内有效"},
    {"name": "周一循环", "value": 8, "desc": "每周一在设定时间段内有效"},
    {"name": "周二循环", "value": 9, "desc": "每周二在设定时间段内有效"},
    {"name": "周三循环", "value": 10, "desc": "每周三在设定时间段内有效"},
    {"name": "周四循环", "value": 11, "desc": "每周四在设定时间段内有效"},
    {"name": "周五循环", "value": 12, "desc": "每周五在设定时间段内有效"},
    {"name": "周六循环", "value": 13, "desc": "每周六在设定时间段内有效"},
    {"name": "周日循环", "value": 14, "desc": "每周日在设定时间段内有效"},
  ];

  @override
  void initState() {
    super.initState();
    // 初始化密码类型和默认时间
    _initKeyboardPwdType();
    _initDefaultTimes();
  }

  // 初始化密码类型
  void _initKeyboardPwdType() {
    switch (widget.usageTimeType) {
      case UsageTimeType.usage:
        _params["keyboardPwdType"] = 3; // 期限密码
        break;
      case UsageTimeType.single:
        _params["keyboardPwdType"] = 1; // 单次密码
        break;
      case UsageTimeType.forever:
        _params["keyboardPwdType"] = 2; // 永久密码
        break;
      case UsageTimeType.clear:
        _params["keyboardPwdType"] = 4; // 删除密码
        break;
      case UsageTimeType.cycle:
        _params["keyboardPwdType"] = 5; // 默认周末循环
        break;
      default:
        _params["keyboardPwdType"] = 3; // 默认期限密码
        break;
    }
  }

  // 初始化默认时间
  void _initDefaultTimes() {
    final now = DateTime.now();
    _params["startDate"] = now;
    _params["endDate"] = now.add(const Duration(days: 30)); // 默认结束时间为30天后
    
    final currentHour = now.hour.toString().padLeft(2, '0');
    final currentMinute = now.minute.toString().padLeft(2, '0');
    _params["startTime"] = "$currentHour:$currentMinute"; 
    _params["endTime"] = "23:59"; // 默认结束时间为当天23:59
  }

  ///获取密码
  void _getPwd() async {
    if (!_validate()) return;

    // 根据不同的密码类型调用不同的API
    switch (widget.usageTimeType) {
      case UsageTimeType.custom:
        await _handleCustomPassword();
        break;
      case UsageTimeType.cycle:
        await _handleCyclePassword();
        break;
      default:
        await _handleRegularPassword();
        break;
    }
  }

  // 处理循环密码
  Future<void> _handleCyclePassword() async {
    Map<String, dynamic> data = {
      "keyboardPwdName": _params["name"],
      "keyboardPwdType": _params["keyboardPwdType"],
      "lockId": widget.lockInfo["lockId"],
    };

    // 添加开始和结束时间（转换为当天的日期+选择的时间）
    final now = DateTime.now();
    final formattedDate = DateTools.formatYMD(now, format: "{y}-{m}-{d}");
    data["startDate"] = "$formattedDate ${_params["startTime"]}:00";
    data["endDate"] = "$formattedDate ${_params["endTime"]}:00";

    print("cycle data:>>${data}");

    EasyLoading.show();
    try {
      var resData = await lockApi.getRandomPwd(int.parse(widget.lockInfo["lockId"]), data);
      // 保存接口返回的密码
      if (resData != null && resData["data"] != null && resData["data"]["keyboardPwd"] != null) {
        _returnedPwd = resData["data"]["keyboardPwd"].toString();
      }
      EasyLoading.showToast("密码获取成功");
      setState(() {
        _getPwded = true;
      });
    } catch (e) {
      EasyLoading.showToast("获取密码失败: $e");
    } finally {
      EasyLoading.dismiss();
    }
  }

  // 处理常规密码（限时/单次/永久/清空码）
  Future<void> _handleRegularPassword() async {
    Map<String, dynamic> data = {
      "keyboardPwdName": _params["name"],
      "keyboardPwdType": _params["keyboardPwdType"],
      "lockId": widget.lockInfo["lockId"],
    };

    // 根据不同的密码类型进行对应处理
    switch (widget.usageTimeType) {
      case UsageTimeType.usage:
          data["startDate"] = DateTools.formatYMD(_params["startDate"], format: "{y}-{m}-{d} {h}:{i}:{s}");
          data["endDate"] = DateTools.formatYMD(_params["endDate"], format: "{y}-{m}-{d} {h}:{i}:{s}");
        break;
      
      case UsageTimeType.single:
        // 单次密码只需要名称和类型，不需要设置时间
        data["startDate"] = DateTools.formatYMD(DateTime.now(), format: "{y}-{m}-{d} {h}:{i}:{s}");
        break;
      
      case UsageTimeType.forever:
        // 永久密码
        data["keyboardPwdType"] = 2;
        data["startDate"] = DateTools.formatYMD(DateTime.now(), format: "{y}-{m}-{d} {h}:{i}:{s}");
        break;
      
      case UsageTimeType.clear:
        // 清空码有效期为24小时
        data["startDate"] = DateTools.formatYMD(DateTime.now(), format: "{y}-{m}-{d} {h}:{i}:{s}");
        break;
      
      default:
        break;
    }

    print("regular data:>>${data}");

    EasyLoading.show();
    try {
      var resData = await lockApi.getRandomPwd(int.parse(widget.lockInfo["lockId"]), data);
      // 保存接口返回的密码
      if (resData != null && resData["data"] != null && resData["data"]["keyboardPwd"] != null) {
        _returnedPwd = resData["data"]["keyboardPwd"].toString();
      }
      EasyLoading.showToast("密码获取成功");
      setState(() {
        _getPwded = true;
      });
    } catch (e) {
      EasyLoading.showToast("获取密码失败: $e");
    } finally {
      EasyLoading.dismiss();
    }
  }

  // 处理自定义密码
  Future<void> _handleCustomPassword() async {
    // 确保开始时间为当前时间（如果用户没有选择）
    DateTime startDate = _params["startDate"] ?? DateTime.now();
    DateTime endDate = forever ? DateTime(2099, 12, 31) : (_params["endDate"] ?? DateTime.now().add(const Duration(days: 30)));
    
    Map<String, dynamic> data = {
      "name": _params["name"],
      "startDate": DateTools.formatYMD(startDate, format: "{y}-{m}-{d} {h}:{i}:{s}"),
      "endDate": DateTools.formatYMD(endDate, format: "{y}-{m}-{d} {h}:{i}:{s}"),
      "keyboardPwd": _params["keyboardPwd"],
      "lockId": widget.lockInfo["lockId"],
      "addType": 2, // 默认网关添加
    };

    print("custom data:>>${data}");

    EasyLoading.show();
    TTLock.getBluetoothState((state) async {
      if (state == TTBluetoothState.turnOn) {
        TTLock.supportFunction(TTLockFuction.managePasscode, widget.lockInfo["lockData"], (isSupport) {
          if (!isSupport) {
            EasyLoading.showToast("该门锁不支持自定义密码");
            EasyLoading.dismiss();
            return;
          }
          TTLock.createCustomPasscode(
            _params["keyboardPwd"],
            forever ? DateTime.now().millisecondsSinceEpoch : startDate.millisecondsSinceEpoch,
            forever ? DateTime(2099, 12, 31).millisecondsSinceEpoch : endDate.millisecondsSinceEpoch,
            widget.lockInfo["lockData"],
            () async {
              // 蓝牙添加成功后，调用API上传密码
              data["addType"] = 1; // 蓝牙添加成功，修改为上传密码
              try {
                await lockApi.sendPwd(data);
                // 自定义密码直接使用用户输入的密码
                _returnedPwd = _params["keyboardPwd"];
                EasyLoading.showToast("密码设置成功");
                setState(() {
                  _getPwded = true;
                });
              } catch (e) {
                EasyLoading.showToast("上传密码失败: $e");
              } finally {
                EasyLoading.dismiss();
              }
            }, (errorCode, errorMsg) {
              // 蓝牙添加失败，调用API创建密码
              _handleBleFailure(data, errorMsg);
            });
        });
      } else {
        // 蓝牙未开启，直接调用API创建密码
        try {
          var resData = await lockApi.sendPwd(data);
          // 自定义密码使用用户输入的密码
          _returnedPwd = _params["keyboardPwd"];
          EasyLoading.showToast("密码获取成功");
          setState(() {
            _getPwded = true;
          });
        } catch (e) {
          EasyLoading.showToast("获取密码失败: $e");
        } finally {
          EasyLoading.dismiss();
        }
      }
    });
  }

  // 处理蓝牙失败的情况
  Future<void> _handleBleFailure(Map<String, dynamic> data, String errorMsg) async {
    EasyLoading.showToast("蓝牙添加失败: $errorMsg，尝试通过网关添加");
    try {
      data["addType"] = 2; // 网关添加
      await lockApi.sendPwd(data);
      // 设置返回密码为用户输入的密码
      _returnedPwd = _params["keyboardPwd"];
      EasyLoading.showToast("密码设置成功");
      setState(() {
        _getPwded = true;
      });
    } catch (e) {
      EasyLoading.showToast("获取密码失败: $e");
    } finally {
      EasyLoading.dismiss();
    }
  }

  // 显示循环类型选择器
  void _showCycleTypePicker() {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          height: 300,
          padding: const EdgeInsets.symmetric(vertical: 20),
          child: Column(
            children: [
              const Text("选择循环类型", style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
              const SizedBox(height: 10),
              Expanded(
                child: ListView.builder(
                  itemCount: _cycleTypes.length,
                  itemBuilder: (context, index) {
                    final item = _cycleTypes[index];
                    return ListTile(
                      title: Text(item["name"]),
                      subtitle: Text(item["desc"], style: const TextStyle(fontSize: 12, color: ThemeVars.colorTextTer)),
                      trailing: _params["keyboardPwdType"] == item["value"] 
                          ? const Icon(Icons.check, color: ThemeVars.colorPrimary) 
                          : null,
                      onTap: () {
                        setState(() {
                          _params["keyboardPwdType"] = item["value"];
                        });
                        Navigator.pop(context);
                      },
                    );
                  },
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  // 显示时间选择器
  void _showTimePicker(String timeType) {
    final timeFormat = RegExp(r'^([0-1]?[0-9]|2[0-3]):([0-5][0-9])$');
    final match = timeFormat.firstMatch(_params[timeType]);
    int hour = 0;
    int minute = 0;
    
    if (match != null) {
      hour = int.parse(match.group(1)!);
      minute = int.parse(match.group(2)!);
    }
    
    showTimePicker(
      context: context,
      initialTime: TimeOfDay(hour: hour, minute: minute),
    ).then((TimeOfDay? time) {
      if (time != null) {
        setState(() {
          _params[timeType] = "${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}";
        });
      }
    });
  }

  bool _validate() {
    if (_params["name"].isEmpty) {
      EasyLoading.showToast("姓名不能为空");
      return false;
    }
    
    if (widget.usageTimeType == UsageTimeType.custom) {
      if (_params["keyboardPwd"].isEmpty) {
        EasyLoading.showToast("密码不能为空");
        return false;
      } else if (_params["keyboardPwd"].length < 6 || _params["keyboardPwd"].length > 9) {
        EasyLoading.showToast("密码长度位6~9位数");
        return false;
      }
    }
    
    return true;
  }

  Widget _tips() {
    String tip = "";
    switch (widget.usageTimeType) {
      case UsageTimeType.usage:
        tip = "密码在生效后的24小时内至少要使用过一次，否则将失效";
        break;
      case UsageTimeType.single:
        tip = "密码试用期为6小时，只能使用一次";
        break;
      case UsageTimeType.forever:
        tip = "密码在24小时内至少要使用过一次，否则将失效";
        break;
      case UsageTimeType.custom:
        tip = "可在锁旁边通过手机蓝牙添加，也可以通过网关远程添加";
        break;
      case UsageTimeType.clear:
        tip = "密码有效期为24小时，在锁上输入后，将使之前使用过的密码都失效";
        break;
      case UsageTimeType.cycle:
        tip = "密码在生效后的24小时内至少要使用过一次，否则将失效";
        break;
    }
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 30),
      child: Text(tip, style: const TextStyle(color: ThemeVars.colorTextTer, fontSize: 14),),
    );
  }

  List<Widget> _getPwdResult() {
    return [
      Padding(
        padding: EdgeInsets.only(top: 50, bottom: 30),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            DecoratedBox(
              decoration: BoxDecoration(
                boxShadow: [BoxShadow(color: ThemeVars.colorPrimaryLight, blurRadius: 15, spreadRadius: 5)],
                borderRadius: BorderRadius.circular(50),
              ),
              child: Icon(Icons.check_circle_rounded, size: 60, color: ThemeVars.colorPrimary,),
            ),
            SizedBox(height: 30,),
            Text("获取成功", style: TextStyle(fontSize: 18),),
            SizedBox(height: 6,),
            Text("密码：${widget.usageTimeType == UsageTimeType.custom ? _params["keyboardPwd"] : _returnedPwd}"),
          ],
        ),
      ),
      Button(
        onPressed: () {},
        child: Text("发送短信"),
      ),
      SizedBox(height: 12,),
      Button(
        type: ButtonType.primaryOutline,
        onPressed: () {
          Stacker.pushNamed(Keys.COMMON_WECHAT_SHARE);
        },
        child: Text("微信分享"),
      ),
    ];
  }

  List<Widget> _usageTime() {
    if (widget.usageTimeType == UsageTimeType.usage || widget.usageTimeType == UsageTimeType.custom) {
      return [
        const SizedBox(height: 12,),
        MenuBlock(
          items: [
            if (widget.usageTimeType == UsageTimeType.custom) MenuBlockItem(
              text: "永久",
              showArrow: false,
              suffix: CupertinoSwitch(
                value: forever,
                activeColor: ThemeVars.colorPrimary,
                onChanged: (value) => setState(() {
                  forever = value;
                }),
              ),
            ),
            if (!forever) MenuBlockItem(
              text: "生效时间",
              suffix: Text(
                DateTools.formatTime(_params["startDate"].millisecondsSinceEpoch, format: "{y}-{m}-{d} {h}:{i}"),
                style: const TextStyle(color: ThemeVars.colorTextTer),
              ),
              onTap: () {
                showDatetimePicker(
                  context: context,
                  initialDateTime: _params["startDate"],
                  minimumDate: currentDate,
                  onchange: (value) => setState(() {
                    if (value != null) _params["startDate"] = value;
                  }),
                );
              },
            ),
            if (!forever) MenuBlockItem(
              text: "失效时间",
              showArrow: true,
              suffix: Text(
                DateTools.formatTime(_params["endDate"].millisecondsSinceEpoch, format: "{y}-{m}-{d} {h}:{i}"),
                style: const TextStyle(color: ThemeVars.colorTextTer),
              ),
              onTap: () {
                showDatetimePicker(
                  context: context,
                  initialDateTime: _params["endDate"],
                  minimumDate: currentDate,
                  onchange: (value) => setState(() {
                    if (value != null)  _params["endDate"] = value;
                  }),
                );
              },
            ),
          ]
        ),
      ];
    } else if (widget.usageTimeType == UsageTimeType.cycle) {
      // 循环密码特殊UI
      return [
        const SizedBox(height: 12,),
        MenuBlock(
          items: [
            MenuBlockItem(
              text: "循环方式",
              suffix: Text(
                _cycleTypes.firstWhere((type) => type["value"] == _params["keyboardPwdType"], orElse: () => {"name": "周末循环"})["name"],
                style: const TextStyle(color: ThemeVars.colorTextTer),
              ),
              onTap: _showCycleTypePicker,
            ),
            MenuBlockItem(
              text: "开始时间",
              suffix: Text(
                _params["startTime"],
                style: const TextStyle(color: ThemeVars.colorTextTer),
              ),
              onTap: () => _showTimePicker("startTime"),
            ),
            MenuBlockItem(
              text: "结束时间",
              suffix: Text(
                _params["endTime"],
                style: const TextStyle(color: ThemeVars.colorTextTer),
              ),
              onTap: () => _showTimePicker("endTime"),
            ),
          ]
        ),
      ];
    } else {
      return [];
    }
  }

  List<Widget> _renderContent() {
    return [
      MenuBlock(
          items: [
            MenuBlockItem(
                text: "姓名",
                showArrow: false,
                suffix: TextField(
                  textAlign: TextAlign.right,
                  decoration: const InputDecoration(
                    hintText: "请给密码命名",
                    isDense: true,
                  ),
                  onChanged: (value) => setState(() {
                    _params["name"] = value;
                  }),
                )
            ),
            if (widget.usageTimeType == UsageTimeType.custom) MenuBlockItem(
                text: "密码",
                showArrow: false,
                suffix: TextField(
                  textAlign: TextAlign.right,
                  decoration: const InputDecoration(
                    hintText: "请设置密码",
                    isDense: true,
                    counterText: "",
                  ),
                  maxLength: 9,
                  onChanged: (value) => setState(() {
                    _params["keyboardPwd"] = value;
                  }),
                )
            ),
          ]
      ),
      ..._usageTime(),
      _tips(),
      Button(
        radius: 6,
        type: ButtonType.primary,
        onPressed: () {
          _getPwd();
        },
        child: const Text("获取密码"),
      ),
    ];
  }


  @override
  Widget build(BuildContext context) {
    return ListView(
      padding: const EdgeInsets.all(ThemeVars.paddingPage),
      children: _getPwded ? _getPwdResult() : _renderContent(),
    );
  }

}